package com.wnxy.controller;


import com.wnxy.entity.CartVo;
import com.wnxy.entity.User;
import com.wnxy.service.CartService;
import com.wnxy.service.UserService;
import com.wnxy.utils.UserTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 购物车表 前端控制器
 * </p>
 *
 * @author 林夕
 * @since 2023-03-11 04:45:21
 */
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    CartService cartService;
    @Autowired
    UserService userService;

    /* 查询登录的用户信息 */
    private User getUser(HttpServletRequest request){
        //拿到保存在token中的用户名
        String userAccount = UserTokenUtil.getUserAccount(request);
        //通过用户名获取用户信息
        User user = userService.getUserByName(userAccount);
        return user;
    }

    /* 加入购物车 */
    @RequestMapping("/addCart")
    public String addCart(Integer weaponId, HttpServletRequest request){
       try {
           User user = getUser(request);
           cartService.addCart(user.getId(), weaponId);
       }catch (Exception e){
            e.printStackTrace();
       }
        return "ok";
    }

    /* 查询购物车的内容 */
    @RequestMapping("/getCart")
    public List<CartVo> getCart(HttpServletRequest request){
        User user = getUser(request);
        List<CartVo> cartVoList = cartService.getCartVo(user.getId());
        return cartVoList;
    }

    /* 改变商品加入购物车的数量及单件商品对应的总额*/
    @RequestMapping("/updateBuyCount")
    public CartVo updateBuyCount(Integer weaponId, Integer count, HttpServletRequest request){
        User user = getUser(request);
        CartVo cartVo = cartService.updateBuyCount(user.getId(), weaponId, count);
        return cartVo;
    }

    /* 勾选商品计算商品总额 */
    @RequestMapping("/totalPrice")
    public BigDecimal totalPrice(@RequestParam("weaponIds[]") Integer[] weaponIds, HttpServletRequest request){
        User user = getUser(request);
        BigDecimal totalPrice = cartService.totalPrice(user.getId(), weaponIds);

        return totalPrice;
    }



}

